package com.joinway.framework.core.repository;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import com.joinway.framework.core.bean.domain.ExceptionConfig;
import com.joinway.framework.core.bean.domain.SystemConfig;
import com.joinway.framework.data.jdbc.repository.TableRepository;

@Service
public class FrameworkRepository implements ApplicationContextAware {

	private final static Logger log = LoggerFactory.getLogger(FrameworkRepository.class);
	
	public static final String SYSTEM_CONFIG_CACHE = "SystemConfig";
	public static final String EXCEPTION_CONFIG_CACHE = "ExceptionConfig";
	
	private static ApplicationContext ctx;
	
	@Autowired(required=false) TableRepository repository;
	
	public static<T> T getBean(Class<T> type){
		return ctx.getBean(type);
	}
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		ctx = applicationContext;
	}

	@Cacheable(value=SYSTEM_CONFIG_CACHE)
	public List<SystemConfig> getSystemConfig() throws Exception {
		return repository != null ? repository.findAll(SystemConfig.class) : null;
	}
	
	@Cacheable(value=EXCEPTION_CONFIG_CACHE)
	public List<ExceptionConfig> getExceptionConfig() throws Exception {
		return repository != null ? repository.findAll(ExceptionConfig.class) : null;
	}
	
	@CacheEvict(value=SYSTEM_CONFIG_CACHE)
	public void clearSystemConfig(){
		log.info("{} cache was cleared", SYSTEM_CONFIG_CACHE);
	}

	@CacheEvict(value=EXCEPTION_CONFIG_CACHE)
	public void clearExceptionConfig(){
		log.info("{} cache was cleared", EXCEPTION_CONFIG_CACHE);
	}
	

}
